<script setup lang="ts">
import logo from "@/assets/logo.png";
import { onMounted, ref, onBeforeUnmount } from "vue";
import { QueryInfo, RunMonitor, StopMonitor } from "./api/index";
import dayjs from "dayjs";

import DeviceStatus from "./views/components/DeviceStatus.vue";
import ParameterSetting from "./views/components/ParameterSetting.vue";
import DataSearch from "./views/components/DataSearch.vue";
const activeName = ref("first");

const runStatus = ref("pending");
//总启动开关
const linkRun = ref(false);
const handleChange = () => {
  //修改状态文本
  runStatus.value = linkRun.value ? "running" : "pending";
  if (linkRun.value) {
    runMonitor();
    //获取设备状态-不带循环
    // getState();
    //开启轮询
    lineFlag.value = true;
    lineLoop();
    //每隔10分钟清除定时器
    setMyInterval(options);
  } else {
    stopMonitor();
    //关闭轮询
    lineFlag.value = false;
    clearTimeout(lineLoopTimer.value);
    lineLoopTimer.value = "";
    // 清除已经设置的 requestAnimationFrame
    if (options.timer) {
      cancelAnimationFrame(options.timer);
    }
  }
};

//开启后台
const runMonitor = () => {
  const post = {
    InputStr: "OperType=RunMonitor",
    JsonStr: [],
  };
  RunMonitor(post).then((res: any) => {
    if (res.code == 200) {
      console.log(`RunMonitor->success`);
    }
  });
};
//关闭后台
const stopMonitor = () => {
  const post = {
    InputStr: "OperType=StopMonitor",
    JsonStr: [],
  };
  StopMonitor(post).then((res: any) => {
    if (res.code == 200) {
      console.log(`StopMonitor->success`);
    }
  });
};

//故障统计
const faultData = ref({
  xList: [],
  yList: [],
});
//日志信息
const logData = ref([]);
//状态统计
const statusData = ref([]);
//开启运行 获取状态
const getState = () => {
  faultData.value.xList = [];
  faultData.value.yList = [];
  const post = {
    InputStr: "OperType=GetFeederState",
    JsonStr: [],
  };
  QueryInfo(post).then((res: any) => {
    if (res.code === 200) {
      const { SSTInfo, StatusInfo, ErrInfo, LogInfo } = res.data;
      statusData.value = SSTInfo;
      feederData.value = StatusInfo;
      logData.value = LogInfo;
      //格式化ErrInfo
      ErrInfo.map((item: any) => {
        faultData.value.yList.push(item.Name);
        faultData.value.xList.push(parseInt(item.Qty));
      });
    }
  });
};

//获取基本信息
interface System {
  SystemName: string;
  CustName: string;
  Factory: string;
  Floor: string;
  Line: string;
  Version: string;
}
//系统信息
const systemData = ref<System>({
  SystemName: "",
  CustName: "",
  Factory: "",
  Floor: "",
  Line: "",
  Version: "",
});

const mailData = ref({});
//收料信息
const feederData = ref([]);
//获取基本信息
const getInfo = () => {
  const post = {
    InputStr: "OperType=GetInitInfo",
    JsonStr: [],
  };
  QueryInfo(post).then((res: any) => {
    if (res.code === 200) {
      const { SystemInfo, MailInfo, FeederInfo, ErrInfo } = res.data;
      systemData.value = JSON.parse(JSON.stringify(SystemInfo[0]));
      mailData.value = JSON.parse(JSON.stringify(MailInfo[0]));
      feederData.value = JSON.parse(JSON.stringify(FeederInfo));
      //格式化ErrInfo
      ErrInfo.map((item: any) => {
        faultData.value.yList.push(item.Name);
        faultData.value.xList.push(parseInt(item.Qty));
      });
      //格式化邮件
      const { FilePath } = mailData.value;
      //将路径中的:\替换为:/
      const newPath = FilePath.replace(/\$/g, "\\");
      mailData.value.FilePath = newPath;
    }
  });
};

const updateSystem = (data: any) => {
  systemData.value = data;
};

//刷新周期
const cycle = ref(3 * 1000);
const timerList = ref<any[]>([]);
const clearAllTimer = () => {
  // 清除所有的定时器
  for (let i = 0; i < timerList.value.length; i++) {
    clearTimeout(timerList.value[i]);
  }
  // 清除列表
  timerList.value = [];
  console.log("clearAllTimerList", timerList.value);
};
/**
 * 固定轮询3秒 loop
 */
const lineLoopTimer = ref();
//异步请求拿到结果 停止轮询
const syncPromiseLine = () => {
  faultData.value.xList = [];
  faultData.value.yList = [];
  const post = {
    InputStr: "OperType=GetFeederState",
    JsonStr: [],
  };
  return new Promise((resolve) => {
    QueryInfo(post)
      .then((res: any) => {
        if (res.code == 200) {
          const { SSTInfo, StatusInfo, ErrInfo, LogInfo } = res.data;
          statusData.value = SSTInfo;
          feederData.value = StatusInfo;
          logData.value = LogInfo;
          //格式化ErrInfo
          ErrInfo.map((item: any) => {
            faultData.value.yList.push(item.Name);
            faultData.value.xList.push(parseInt(item.Qty));
          });
          //如果检查到返回值为Y则要重新启动RunMonitor
          if (res.outputStr == "Y") {
            runMonitor();
          }
          resolve(1);
        }
      })
      .catch((err) => {
        resolve(1);
      });
  });
};
//控制轮询的间隔时间 并在指定时间执行请求
const pollingPrimiseLine = () => {
  return new Promise((resolve) => {
    lineLoopTimer.value = setTimeout(async () => {
      const result = await syncPromiseLine();
      resolve(result);
    }, cycle.value);
    timerList.value.push(lineLoopTimer.value);
  });
};
//轮询入口
const lineFlag = ref(true);
const startPollingLine = async () => {
  clearTimeout(lineLoopTimer.value);
  lineLoopTimer.value = "";
  let needPolling = await syncPromiseLine();
  console.log(
    `output->needPolling, lineFlag.value`,
    needPolling,
    lineFlag.value
  );
  while (needPolling && lineFlag.value) {
    needPolling = await pollingPrimiseLine();
  }
  console.log("设备状态轮询请求处理完成！");
};
const lineLoop = async () => {
  await startPollingLine();
  console.log("设备状态请求被clearTimeOut 这里不会被执行");
};

//requestAnimationFrame
const setMyInterval = (options: any) => {
  const requestAnimationFrame =
    window.requestAnimationFrame || window.webkitRequestAnimationFrame;
  let i = 1;
  let count = 1;
  options.timer = options.timer || null;
  const loop = () => {
    options.timer = requestAnimationFrame(loop);
    if (i % 60 === 0) {
      // 此处 60 代表屏幕刷新率为60HZ，即代表此处每隔一秒执行一次
      const timeout = options.timeout || 1000;
      if (count % parseInt((timeout / 1000).toString()) === 0) {
        // 每隔多少秒调用一次回调函数，此处timeout应为1000的倍数
        options.callback && options.callback();
      }
      count++;
    }
    i++;
  };
  options.timer = requestAnimationFrame(loop);
};
let options = {
  timer: null,
  callback: () => {},
  timeout: 1000,
};

const tenMinutes = 10 * 60 * 1000;
options.timeout = tenMinutes;
let tempTimer = ref();
options.callback = () => {
  //当开启的状态每隔10分钟清除
  if (linkRun.value) {
    // 当前lineFlag为true且lineLoopTimer true 清除GetLineState定时器
    if (lineFlag.value && lineLoopTimer.value) {
      clearTimeout(lineLoopTimer.value);
      lineLoopTimer.value = "";
      clearAllTimer();
      lineFlag.value = false;
      tempTimer.value = setTimeout(() => {
        lineFlag.value = true;
        lineLoop();
        clearTimeout(tempTimer.value);
        tempTimer.value = "";
        console.log(`output->clear success`);
      }, 0);
      console.log("clearLineLoopTimer", lineLoopTimer.value);
    }
  }
};

const current = dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss");
let currentTime = ref(current);
let timerID = ref();
onMounted(() => {
  timerID.value = setInterval(() => {
    currentTime.value = dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss");
  }, 1000);
  getInfo();
});
onBeforeUnmount(() => {
  clearInterval(timerID.value);
  timerID.value = null;
});
</script>

<template>
  <div class="overflow-hidden main">
    <div class="header">
      <img class="logo" :src="logo" width="110" height="60" />
      <div class="header-title">
        <p class="text-4xl">{{ systemData.SystemName || "供料器看板系统" }}</p>
      </div>
      <div class="user-info">{{ currentTime }}</div>
    </div>
    <!-- 客户&线别信息 -->
    <div class="flex justify-between">
      <div class="flex">
        <p class="ml-3 w-96">客户名称：{{ systemData.CustName }}</p>
        <p class="ml-3 w-80">厂区：{{ systemData.Factory }}</p>
        <p class="ml-3 w-80">楼层：{{ systemData.Floor }}</p>
        <p class="ml-7">线别：{{ systemData.Line }}</p>
      </div>
      <div class="mr-4">版本：{{ systemData.Version }}</div>
    </div>
    <section class="flex mt-2">
      <div class="content">
        <el-tabs v-model="activeName">
          <el-tab-pane label="设备状态" name="first">
            <DeviceStatus
              :faultData="faultData"
              :feederData="feederData"
              :statusData="statusData"
              :logData="logData"
            />
          </el-tab-pane>
          <el-tab-pane label="参数设置" name="second">
            <ParameterSetting
              :systemData="systemData"
              :mailData="mailData"
              @updateSystem="updateSystem"
            />
          </el-tab-pane>
          <!-- <el-tab-pane label="设备参数" name="third">设备参数</el-tab-pane> -->
          <el-tab-pane label="数据查询" name="fourth">
            <DataSearch />
          </el-tab-pane>
        </el-tabs>
        <div class="run-status flex">
          <el-switch
            v-model="linkRun"
            size="large"
            style="
              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            "
            @change="handleChange"
          />
          <div class="ml-2">
            <span
              v-if="runStatus === 'running'"
              class="text-green-500"
              type="success"
              >运行中</span
            >
            <span
              v-if="runStatus === 'pending'"
              class="text-amber-500"
              type="warning"
              >待启动</span
            >
          </div>
        </div>
      </div>
    </section>
  </div>
</template>
<style lang="less">
.main {
  background: #0d0f20;
  color: #fff;
  font-size: 1.5rem;
}

.header {
  position: relative;
  height: 80px;
  color: #fff;
  line-height: 80px;
  text-align: center;
  img {
    position: absolute;
    object-fit: contain;
    top: 0;
    left: 10px;
  }

  .logo {
    height: 80px;
    align-items: center;
  }

  .user-info {
    position: absolute;
    top: 0;
    right: 20px;
  }

  .header-title {
    p {
      line-height: 80px;
    }
  }
}

.content {
  position: relative;
  width: 100%;
  height: calc(100vh - 90px);
  overflow: hidden;
  padding: 0 15px;
}

.el-tabs__item {
  color: #fff !important;
  font-size: 1.5rem !important;
  padding-bottom: 10px !important;
}
.el-tabs__item.is-active {
  color: var(--el-color-primary) !important;
}

.el-tabs__nav-wrap::after {
  height: 1px !important;
  background-color: #1c324f !important;
}
.el-tabs__active-bar {
  height: 4px !important;
}
.run-status {
  position: absolute;
  right: 12px;
  top: -5px;
}
</style>
